﻿using ProjectGamer.DataModels;
using ProjectGamer.Web.DbAdapters.Adapters;
using ProjectGamer.Web.DbAdapters.IAdapters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using ProjectGamer.Web.Models;

namespace ProjectGamer.Web.Controllers
{
    public class RentalController : ApiController
    {
        IGameAdapter _adapter = new GameAdapter();

        // GET api/rental
        [ActionName("user")]
        public IHttpActionResult Get(string id)
        {
            List<Models.RentalVM> rentals = _adapter.GetAllRentalsForRenter(id);
            return Ok(rentals);
        }
        // POST api/rental/rent/:id
        [ActionName("rent")]
        public IHttpActionResult Post1(int id)
        {
            Rental rental = new Rental();
            Game game = _adapter.GetGameForRental(id);
            if (game.RentPrice > 0)
            {
                RentalVM rentalvm = _adapter.AddRental(game.Id, User.Identity.GetUserId(), "rent");
                return Ok(rentalvm);
            }
            
            return Unauthorized();
        }

        // POST api/rental/buy/:id
        [ActionName("buy")]
        public IHttpActionResult Post2(int id)
        {
            Rental rental = new Rental();
            Game game = _adapter.GetGameForRental(id);
            if (game.SellPrice > 0)
            {
                RentalVM rentalvm = _adapter.AddRental(game.Id, User.Identity.GetUserId(), "buy");
                return Ok(rentalvm);
            }

            return Unauthorized();
        }

        // POST api/rental/trade/:id
        [ActionName("trade")]
        public IHttpActionResult Post3(int id)
        {
            Rental rental = new Rental();
            Game game = _adapter.GetGameForRental(id);
            if (game.WillTrade)
            {
                RentalVM rentalvm = _adapter.AddRental(game.Id, User.Identity.GetUserId(), "trade");
                return Ok(rentalvm);
            }

            return Unauthorized();
        }

        //PUT api/rental/
        public IHttpActionResult Put([FromBody] Rental rental)
        {
            if (_adapter.GetUserId(rental.GameId) == User.Identity.GetUserId())
            {
                rental = _adapter.UpdateRental(rental);
                return Ok(rental);
            }
            return Unauthorized();
        }
    }
}
